﻿using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request.ReduceFee;
using Common.Contract.Customer.Response.ReduceFee;
using Common.Contract.Paging;
using Common.Service.Command;
using Customer.Model.Interface;
using Customer.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Customer.Core.ServiceCommand.ReduceFee
{
    public class RetrieveCustomerFinanceInfoByCifServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveCustomerFinanceInfoByCifRequest, RetrieveCustomerFinanceInfoByCifResponse>
    {
        #region Properties
        public string Cif;
        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        #endregion
        public RetrieveCustomerFinanceInfoByCifServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveCustomerFinanceInfoByCifRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (string.IsNullOrEmpty(request.Cif))
            {
                throw new ArgumentException("Cif Customer must be set", "request");
            }
            else
            {
                Cif = Request.Cif;
            }
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
        }

        protected override bool OnExecute(RetrieveCustomerFinanceInfoByCifResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            List<CustomerFinanceInfoRecord> records = new List<CustomerFinanceInfoRecord>();
            List<CustomerFinanceInfo> customerFinance = Providers.Customers.RetrieveCustomerFinanceInfoByCif(Cif);
            if (customerFinance != null && customerFinance.Count > 0)
            {
                records = customerFinance.Select(x => new CustomerFinanceInfoRecord
                {
                    Cif = x.Cif,
                    Content = Request.Lang.Equals("en") ? x.ContentEn : x.Content,
                    N1 = x.N1,
                    N2 = x.N2,
                    N = x.N,
                    Note = x.Note
                }).ToList();
            }
            response.Records = records;
            response.Page = new PageRecord
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                TotalRecords = totalRecord
            };

            return isSuccess;
        }
    }
}
